# ==============读取==================
"""
f = open('stu.txt','r',encoding='utf-8')
# print(f.read())     # 读取文件所有内容，返回的是字符串
print(f.readlines())        # 读取文件所有内容，返回的是一个列表

f.close()       # 关闭文件，在不操作的时候，一定要记得关闭
"""
# 使用with上下文管理，进行文件读取（不需要关闭文件，自己会做这个事）
"""
with open('stu.txt','r',encoding='utf-8') as f:
    print(f.read())
"""
# ============覆盖写入：w===========================
"""
with open('stu.txt','w',encoding='utf-8') as f:
    # f.write("张三\n李四\n王五\n")       # 写入字符串
    f.writelines(['李四1\n','王五2\n','张三3\n'])     # 写入列表
"""
# =============追加写入：a=========================
"""
with open('stu.txt','a',encoding='utf-8') as f:
    # f.write("英鸿年\n秋\n")
    f.writelines(['suki\n','tiki\n','wave\n'])
"""
# =================修改方法一=========================
"""
with open('stu.txt','r',encoding='utf-8') as f:
    all_data = f.read()     # 先拿到文件中的全部内容为字符串
# 处理完的字符串，需要重新赋值才可以，字符串是不可变的对象
all_data = all_data.replace('wave','waves')      # 我想把所有的wave换成waves

with open('stu.txt','w',encoding='utf-8')as f:
    f.write(all_data)
"""
#================修改方法二==========================
"""
with open('stu.txt','r',encoding='utf-8') as f:
    all_lines = f.readlines()
all_lines2 = []
num = 0
for i in all_lines:
    if i.strip() != '秋英鸿年':
        all_lines2.append(i)
for i in range(len(all_lines) - len(all_lines2)):
    all_lines2.append('tester\n')
# print(all_lines2)
with open('stu.txt','w',encoding='utf-8') as f:
    f.writelines(all_lines2)
"""
# ======================删除============================
with open('stu.txt','r',encoding='utf-8') as f:
    all_lines = f.readlines()
for i in all_lines:
    if i.strip() =='李四1':
        all_lines.remove(i)
# print(all_lines)
with open('stu.txt','w',encoding='utf-8') as f:
    f.writelines(all_lines)




"""
open：打开文件函数
参数1：文件位置/文件路径
参数2：文件模式：r可以读、w覆盖写入、a是追加写入
参数3：编码，一般是：encoding = 'utf-8'
"""




